# -*- coding:utf-8 -*-
# @Time: 2020/7/13 17:09
# @Author: liupengfei
# @File: serializers.py
import json

from rest_framework import serializers

from utils.serializersfield import DelayTimeCharField
from .models import Comment
from apps.member.serializers import MemberInfoSerializer
from ..models import MemberRecord
from ...system.serializers import UploadSerializer


class CommentSerializers(serializers.ModelSerializer):
    childs_count = serializers.SerializerMethodField()
    user_info = serializers.SerializerMethodField()
    is_allow_delete = serializers.SerializerMethodField()  # 是否允许删除
    model_name = serializers.SerializerMethodField()
    create_time = DelayTimeCharField()
    images = serializers.SerializerMethodField()
    is_like = serializers.SerializerMethodField()
    parse_content = serializers.SerializerMethodField()

    def get_is_allow_delete(self, obj):
        user = self.context['request'].user
        if user.id == obj.user.id:
            return True
        return False

    def get_images(self, obj):
        return UploadSerializer(obj.images, many=True).data

    def get_is_like(self, obj):
        user = self.context['request'].user
        if user.is_authenticated:
            return MemberRecord.check_user_operate(user, Comment.get_content_type(), obj.id, MemberRecord.LIKE)
        return False

    def get_model_name(self, obj):
        return 'Comment'.lower()

    def get_user_info(self, obj):
        return MemberInfoSerializer(instance=obj.user.member).data

    def get_childs_count(self, obj):
        comments = Comment.objects.filter(parent=obj)
        return comments.count()

    def get_parse_content(self, obj):
        if obj.parse_content:
            return json.loads(obj.parse_content)
        return []

    class Meta:
        model = Comment
        fields = ('id', 'content', 'parse_content', 'create_time', 'like_count', 'childs_count',
                  'is_allow_delete', 'user_info', 'model_name', 'is_like', 'images')


class CommentChildSerializers(serializers.ModelSerializer):
    pass
